/**
 * 以插件形式、被其他业务页面调用
 */
var WN_USER = (function() {
	
	/**
	 * 客户基础信息检索 baseinfo
	 */
	function get(userUUID) {
		var user = null;
		if (userUUID) {
			$.ajax({ 
		        type: "POST", 
		        url: WeKnow.getRealPath() + "/wncrm_user_search_dosearch.do/search_useruuid", 
		        dataType: "json",
		        data: {
		        	userUUID: userUUID
		        },
		        async: false,
		        success:function(data) {
		        	if (data.errcode == 0) {
		        		if (data.user) {
		        			user = data.user;
		        		}
		        	}
		        }
			});
		}
		
		return user;
	}
	
	/**
	 * 客户检索 （同 客户中心检索）
	 * search_id 唯一识别id
	 * search_name 姓名
	 * search_phone 电话
	 * result_position 检索结果显示target jquery对象（必须）
	 * dropdown_menu_style 下拉菜单的style
	 * result_norecord_msg 没有检索到数据时的message
	 * result_choose_callback 有检索结果时，选择结果时的回调
	 */
	function search(options) {
		if (options) {
//			if (!options.search_id &&
//				!options.search_name &&
//				!options.search_phone) {
//				return false;
//			}
			if (options.result_position && options.result_position.length) {
				$.post(
					(function() {
						if (options.data_isolation && 'no' == options.data_isolation) { // 不隔离
							return WeKnow.getRealPath()+'/wncrm_user_search/noisolation';
						} else {
							return WeKnow.getRealPath()+'/wncrm_user_search_dosearch.do/search';
						}
					})(),
					(function() {
						var params = {};
						if (options.search_id) {
							params.search_id = options.search_id;
						}
						if (options.search_name) {
							params.search_name = options.search_name;
						}
						if (options.search_phone) {
							params.search_phone = options.search_phone;
						}
						return params;
					})(),
					function(data, status) {
						if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
						if (data.errorcode == 0) {
							var users = data.userList;
							var $userDropdownMenu = null;
							$('ul.dropdown-menu.user-dropdown-menu').remove();
							var e = '<ul class="dropdown-menu user-dropdown-menu" style="max-height: 250px; padding-top: 0px;padding-bottom: 0px; min-width: 300px; overflow-y:auto;">';
							e += '<li>';
								e += '<table class="table table-hover table-condensed table-bordered" style="margin-bottom: 0px;">';
										e += '<thead class="bg-default">';
											e += '<tr>';
												e += '<td width="35%">姓名</td>';
												e += '<td width="15%">性别</td>';
												e += '<td width="15%">年龄</td>';
												e += '<td width="35%">手机号</td>';
											e += '</tr>';
										e += '</thead>';
										e += '<tbody></tbody>';
								e += '</table>'
							e += '</li>';
							e += '</ul>';
							$userDropdownMenu = options.result_position.after(e).next('ul.dropdown-menu.user-dropdown-menu');
							if (users && users.length) {
//								e += '</ul>';
								$(users).each(function(idx, userShell) {
									var user = userShell.base;
									e = '';
									e += '<tr';
										if (idx == 0) {
											e += ' class="active"';
										}
										e += ' data-tagname="' + (user.name != null ? user.name : user.phone) + '"';
										e += ' data-useruuid="' + user.userUUID + '"';
										e += ' data-freest="' + userShell.freeSt + '"';
//										e += ' style="height: 45px; padding: 1px;"'
									e += '>';
//										e += '<td style="white-space:nowrap;">' + user.name + '</td>';
										e += '<td>' + user.name + '</td>';
										e += '<td>';
										if (user.gender == 1) {
											e += ' 男';
										} else if (user.gender == 2) {
											e += ' 女';
										}
										e += '</td>';
										e += '<td style="white-space:nowrap;">';
										if (user.age != null) {
											e += ' ' + user.age + '岁';
										} else if (user.birthday != null && WN_AGE_UTIL) {
											if (!WN_AGE_UTIL) {
												WeKnow.include(WeKnow.getRealPath() + '/js/pc/lib/wn-age-util.js')
											}
											e += ' ' + WN_AGE_UTIL.exchangeAge(new Date(user.birthday).format('yyyy-MM-dd'));
										}
										e += '</td>';
										e += '<td style="white-space:nowrap;">' + (user.phone?user.phone:'') + '</td>';
									e += '</tr>';
									var $oneUser = $(e).appendTo($userDropdownMenu.find('tbody'));
									$oneUser.on('click', function(e) {
										if (options.result_choose_callback) {
											options.result_choose_callback(user);
										}
										$userDropdownMenu.remove();
										e.stopPropagation();
									});
								});
							} else {
								if (options.result_norecord_msg) {
									$userDropdownMenu = options.result_position.after(e).next('ul.dropdown-menu.user-dropdown-menu');
									e = '';
									e += '<tr>';
										e += '<td colspan="4">';
											e += options.result_norecord_msg
										e += '</td>';
									e += '</tr>';
									$(e).appendTo($userDropdownMenu.find('tbody'));
								}
							}
							
							if ($userDropdownMenu && $userDropdownMenu.find('tbody>tr').length) {
								$('body').one('click', function() {
									$userDropdownMenu.remove();
								});
								// 左边对齐
								$userDropdownMenu.css('left', options.result_position.css('left'));
//								$userDropdownMenu.offset({left: options.result_position.position().left});
								
								// 纵向滚动条
								if ($userDropdownMenu.find('li').length >= 8) {
									$userDropdownMenu.css('overflow-y', 'auto');
								}
								$userDropdownMenu.show();
								
								// 鼠标移动事件
								$userDropdownMenu.find('li[data-useruuid]').on('mouseover', function() {
									$(this).addClass('active').siblings('li').removeClass('active');
								});
							}
						} else {
							WeKnow.systemMsg('系统异常');
						}
					}
				);
			}
		}
	}
	
	/**
	 * 移除 检索结果
	 */
	function remove() {
		$('ul.dropdown-menu.user-dropdown-menu').remove();
	}
	
	
	/**
	 * result_choose_callback 有检索结果时，选择结果时的回调 or 添加成功后回调
	 * 其他参数同search
	 */
	function add(options) {
		var e = '';
		e += '<div class="modal fade" tabindex="-1" role="dialog">';
			e += '<div class="modal-dialog" role="document">';
				e += '<div class="modal-content">';
					e += '<div class="modal-header">';
						e += '<h4 class="modal-title">';
							e += '新建';
							e += '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
						e += '</h4>';
					e += '</div>';
					e += '<div class="modal-body">';
						e += '<div class="row">';
							e += '<div class="col-xs-offset-2 col-xs-2 text-right">';
								e += '<span class="required">姓名</span>';
							e += '</div>';
							e += '<div class="col-xs-6">';
								e += '<div class="has-feedback">';
									e += '<input type="text" class="form-control" name="name" maxlength="10" AUTOCOMPLETE="off" value="' + (options.user_name ? options.user_name : '') + '">';
								e += '</div>';
							e += '</div>';
						e += '</div>';
						e += '<div class="row" style="margin-top: 5px;">';
							e += '<div class="col-xs-offset-2 col-xs-2 text-right">';
								e += '<span class="required">性别</span>';
							e += '</div>';
							e += '<div class="col-xs-6">';
								e += '<label class="radio-inline"><input type="radio" name="gender" value="1">男</label>';
								e += '<label class="radio-inline"><input type="radio" name="gender" value="2">女</label>';
							e += '</div>';
						e += '</div>';
						e += '<div class="row" style="margin-top: 5px;">';
							e += '<div class="col-xs-offset-2 col-xs-2 text-right">';
								 e += '<span>手机号</span>';
							e += '</div>';
							e += '<div class="col-xs-6">';
								e += '<input type="text" class="form-control" name="phone" maxlength="11" AUTOCOMPLETE="off"/>';
							e += '</div>';
						e += '</div>';
						e += '<div class="row" style="margin-top: 5px;">';
							e += '<div class="col-xs-offset-2 col-xs-2 text-right">';
								 e += '<span>年龄</span>';
							e += '</div>';
							e += '<div class="col-xs-6">';
								e += '<div class="input-group">';
									e += '<input type="text" class="form-control" name="age" maxlength="3"/>';
									e += '<span class="input-group-addon">岁</span>';
								e += '</div>';
							e += '</div>';
						e += '</div>';
//						e += '<div class="row" style="margin-top: 5px;">';
//							e += '<div class="col-xs-offset-2 col-xs-2 text-right">';
//								 e += '<span>标签</span>';
//							e += '</div>';
//							e += '<div class="col-xs-6">';
//								e += '<div class="dropdown tags_dropdown" id="div_report_item">';
//									e += '<input name="tags" class="form-control" placeholder="多个标签时用空格隔开" AUTOCOMPLETE="off"/>';
//								e += '</div>';
//							e += '</div>';
//						e += '</div>';
						
						e += '<div class="row" style="margin-top: 5px;">';
							e += '<div class="col-xs-offset-2 col-xs-2 text-right">';
								 e += '<span>标签</span>';
							e += '</div>';
							e += '<div class="col-xs-6">';
								e += '<select class="select2 form-control" name="tags" multiple="multiple" data-placeholder="请选择标签"></select>';
							e += '</div>';
						e += '</div>';
					e += '</div>';
					e += '<div class="modal-footer">';
						e += '<div class="row">';
							e += '<div class="col-xs-10 text-right">';
								e += '<button type="button" name="cancel" class="btn btn-default" data-dismiss="modal">取消</button>';
								e += '<button type="button" name="save" class="btn btn-primary">保存</button>';
							e += '</div>';
						e += '</div>';
					e += '</div>';
				e += '</div>';
			e += '</div>';
		e += '</div>';
		
		var $newUserModel = $(e).appendTo('body').modal('show');
		$newUserModel.on('show.bs.modal', function() {
			// 加载多选下拉框所有的js,css
			WeKnow.include('/plugins/select2/dist/css/select2.css');
			WeKnow.include('/plugins/select2/dist/css/select2-bootstrap.css');
			WeKnow.include('/plugins/select2/dist/js/select2.min.js');
		}).on('shown.bs.modal', function() {
			$newUserModel.find('input[name="name"]').focus();
			
			// 加载多选下拉框所有的js,css
			WeKnow.include('/plugins/select2/dist/css/select2.css');
			WeKnow.include('/plugins/select2/dist/css/select2-bootstrap.css');
			WeKnow.include('/plugins/select2/dist/js/select2.min.js');
			
			var postUrl =  WeKnow.getRealPath() + '/wncrm_healthdata.do/search_tags';
			$.post(postUrl, {}, function(data, status) {

				if (!WeKnow.filterAjaxResult(data)) return false;
				
				if(data.errorcode == 0) {
					var list = data.allTags;
					// 有数据时
					if ( list.length ) {
						var ope = ''; 
						// 循环生成下拉 标签选项
						$(list).each(function(idx, tag) {
							ope+='<option value="'+tag.tagName+'">'+tag.tagName+'</option>';
						});
						$newUserModel.find('.select2').append(ope);
						// Select2
			            jQuery(".select2").select2({
			                width: '100%'
			            });
					}
				}
			});
			
			
		}).on('hidden.bs.modal', function() {
			$newUserModel.remove();
		});
		
		// 输入名字时自动检索
		var autoSearch = null;
		$newUserModel.find('input[name="name"]').on('input', function() {
			if (autoSearch) clearTimeout(autoSearch);
			
			var $that = $(this);
			$that.next('ul.user-dropdown-menu').remove();
			
			var searchKey = $.trim($that.val());
			if (searchKey.length) {
				autoSearch = setTimeout(function() {
					options.result_position = $that;
					options.search_name = searchKey;
//					options.dropdown_menu_style = 'width: 100%;';
					var callback = options.result_choose_callback;
					options.result_choose_callback = function(user) {
						$newUserModel.modal('hide')
						callback(user);
					}
					search(options);
				}, 300);
			}
		});
		
//		// 检查项目自动匹配
//		$newUserModel.find('input[name="tags"]').on('input', function() {
//	
//			if (autoSearch) clearTimeout(autoSearch);
//			
//			var $that = $(this);
//			
//			var searchKey = $that.val();
//			autoSearch = setTimeout(function() {
//				getTags(searchKey);
//			}, 300);	
//		});
		
		// 保存
		$newUserModel.find('button[name="save"]').on("click", function(e) {
			e.stopPropagation();
			createUser($newUserModel, options.result_choose_callback);
		});
	}
	
	function createUser($newUserModel, callbackSuccess, user) {
		if (!user) {
			user = {};
			// 姓名
			user.name = $.trim($newUserModel.find('input[name="name"]').val());
			if (!user.name.length) {
				WeKnow.errorMsg("请输入姓名");
				$newUserModel.find('input[name="name" ]').focus();
				return false;
			}
			// 性别
			if (!$newUserModel.find('input[name="gender"]:checked').length) {
				WeKnow.errorMsg("请选择性别");
				$newUserModel.find('input[name="gender"]').first().focus();
				return false;
			}
			user.gender = $newUserModel.find('input[name="gender"]:checked').val();
			
			// 手机号
			user.phone = $.trim($newUserModel.find('input[name="phone"]').val());
			if (!user.phone.length) {
//				WeKnow.errorMsg("请输入手机号");
//				$newUserModel.find('input[name="phone"]').focus();
//				return false;
			} else {
				if (!MY_VALIDATOR) {
					WeKnow.include(WeKnow.getRealPath() + '/js/pc/lib/wn-validator.js')
				}
				if (!MY_VALIDATOR.checkMobile(user.phone)) {
					WeKnow.errorMsg("手机号格式不正确");
					$newUserModel.find('input[name="phone"]').focus();
					return false;
				}
			}
			
			// 手机号
			user.age = $.trim($newUserModel.find('input[name="age"]').val());
			if (!user.age.length) {
			} else {
				if (!MY_VALIDATOR) {
					WeKnow.include(WeKnow.getRealPath() + '/js/pc/lib/wn-validator.js')
				}
				if (!MY_VALIDATOR.isNumber(user.age)) {
					WeKnow.errorMsg("年龄格式不正确");
					$newUserModel.find('input[name="age"]').focus();
					return false;
				}
			}
			// add by zhengxb 2018.9.29 用户标签  start--------------------------------
			var tagName =  $.trim($newUserModel.find('select[name="tags"]').val());

			if (tagName.length){
				user.tagName = tagName;
			}
			// add by zhengxb 2018.9.29 用户标签  end  --------------------------------
		}
		
		WeKnow.loading();
		$.ajax({ 
	        type: "POST", 
	        url: WeKnow.getRealPath() + "/wncrm_healthdata.do/create", 
	        dataType: "json",      
	        contentType: "application/json",               
	        data: JSON.stringify(user),
	        async: false,
	        success:function(data) {
	        	if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errorcode == 0) {
	        		WeKnow.successMsg("新建成功");
	        		$newUserModel.find('button[name="cancel"]').click();
	        		if (callbackSuccess) { // 回调
	        			user.userUUID = data.userUUID;
	        			callbackSuccess(user);
					}
				} else if (data.errorcode == -101) {
					var representative = data.representative;
					WeKnow.modal(
						{
							title: '确认',
							message: (function() {
								var e = '';
								e += representative.name + ' 和新建客户的手机号相同，是同一家庭成员吗？';
								e += '<br>若不是同一家庭的成员，请更换手机号。';
								return e;
							})(),
							buttons:[
								{
									name:'不是',
									class:'btn md-close btn-default',
									onClick: function() {
										WeKnow.closeModal();
										WeKnow.errorMsg('手机已被注册，请更换');
										$newUserModel.find('input[name="phone"]').focus();
										return false;
						        	}
								},
						        {
									name:'是',
									class:'btn md-close btn-primary',
						        	onClick: function() {
						        		WeKnow.closeModal();
						        		user.userUUID = representative.userUUID;
						        		user.relationShip = "家人";
						        		createUser($newUserModel, callbackSuccess, user);
						        	}
						        }
							]
						}
					);
				} else {
					WeKnow.systemMsg("系统异常");
		        	return false;
				}
	        },
	        error: function() {
	        	WeKnow.systemMsg("系统异常");
	        	return false;
	        }
		});
		WeKnow.closeLoading();
	}
	
	return {
		get: get,
		search: search,
		add: add,
		remove: remove
	}
})();

//键盘操作
$(document).ready(function() {
	$(document).keydown(function (event) {
		var $userDropdownMenu = $('ul.user-dropdown-menu');
		if ($userDropdownMenu && $userDropdownMenu.length) {
			var $activeUser = $userDropdownMenu.find('tr.active');
			if ($activeUser && $activeUser.length) {
				switch (event.keyCode) {
			    case 13: // Enter
			    	$activeUser.click();
			        break;
			    case 38: // 方向键-上
			    	var $upUser = $activeUser.prev('tr[data-useruuid]');
			    	if ($upUser && $upUser.length) {
			    		$upUser.addClass('active');
			    		$activeUser.removeClass('active');
			    		
			    		// 滚动条
			    		$userDropdownMenu.scrollTop($userDropdownMenu.scrollTop() - $activeUser.height());
			    	}
			        break;
			    case 40: // 方向键-下
			    	var $downUser = $activeUser.next('tr[data-useruuid]');
			    	if ($downUser && $downUser.length) {
			    		$downUser.addClass('active');
			    		$activeUser.removeClass('active');
			    		
			    		// 滚动条
			    		$userDropdownMenu.scrollTop($userDropdownMenu.scrollTop() + $activeUser.height());
			    	}
			        break;
			    };
			}
		}
		
	    return true;
	});
});